<template>
    <view class="home">
        <nav-bar></nav-bar>
        <carousel :list="bannerList"></carousel>
        <category-list :category-list="categoryList"></category-list>
        <hot-recomm :hot-list="hotList"></hot-recomm>
        <guess :guess-list="newList" title="新鲜好物"></guess>
        <guess :guess-list="guessList" title="猜你喜欢"></guess>
    </view>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { storeToRefs } from "pinia";
import { onLoad, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
import useHomeStore from "@/pinia/modules/homeStore";
import type { PageParams } from "@/types/home";
import NavBar from "@/pages/home/components/navBar/navBar.vue";
import Carousel from "@/components/carousel.vue";
import CategoryList from "@/pages/home/components/categoryList/categoryList.vue";
import HotRecomm from "@/pages/home/components/hotRecomm/hotRecomm.vue";
import Guess from "@/components/guess.vue";

const homeStore = useHomeStore();

const { bannerList, categoryList, hotList, guessList, guessListTotal, newList } = storeToRefs(homeStore);

/*获取猜你喜欢列表的分页参数*/
const pageParams = reactive<PageParams>({
    page: 1,
    pageSize: 10,
});

/*获取轮播图的函数*/
const fetchBanner = async () => {
    try {
        await homeStore.fetchBanner(1);
    } catch (error: any) {
        await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
    }
};

/*获取分类导航的函数*/
const fetchCategory = async () => {
    try {
        await homeStore.fetchCategory();
    } catch (error: any) {
        await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
    }
};

/*获取热门推荐的函数*/
const fetchHot = async () => {
    try {
        await homeStore.fetchHot();
    } catch (error: any) {
        await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
    }
};

/*获取新鲜好物的函数*/
const fetchNew = async () => {
    try {
        await homeStore.fetchNew(10);
    } catch (error: any) {
        await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
    }
};

/*获取猜你喜欢的请求函数*/
const fetchGuess = async () => {
    try {
        await homeStore.fetchGuess(pageParams);
    } catch (error: any) {
        await uni.showToast({ title: error.message, icon: "error", duration: 2000 });
    }
};

/*刷新猜你喜欢的函数*/
const refreshGuess = async () => {
    pageParams.page = 1;
    guessList.value = [];
    await fetchGuess();
    uni.stopPullDownRefresh();
};

onLoad(async () => {
    await Promise.all([fetchBanner(), fetchCategory(), fetchHot(), fetchGuess(), fetchNew()]);
});

onReachBottom(() => {
    if (guessList.value.length >= guessListTotal.value) return uni.showToast({ title: "商品加载完毕", icon: "error", duration: 2000 });
    fetchGuess();
});

onPullDownRefresh(() => {
    refreshGuess();
});

</script>

<style scoped lang="scss">
.home {
    background-color: #f7f7f7;
}
</style>
